package cn.edu.scnu.controller;

import cn.edu.scnu.entity.Movie;
import cn.edu.scnu.service.GradeService;
import cn.edu.scnu.service.MovieService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
public class GradeController {
    @Autowired
    private MovieService movieService;
    @Autowired
    private GradeService gradeService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/grade")
    public String grade(Model model) {
        if (redisTemplate.opsForValue().get("userLogin") != null) {
            model.addAttribute("userLogin",
                    redisTemplate.opsForValue().get("userLogin"));
        }
        return "grade";
    }

    // 展示排行榜
    @RequestMapping("/grade/movieList")
    @ResponseBody
    public List<Movie> showGradeList(@RequestParam("query") String query) {
        List<Movie> movieGradeList = new ArrayList<>();
        if (query.equals("score")) {
            // 好评榜
            movieGradeList = gradeService.sortMovieByScore();
        }
        else if (query.equals("weekPopularity")) {
            // 周榜
            movieGradeList = gradeService.sortMovieByWeekPopularity();
        } else if (query.equals("monthPopularity")) {
            // 月榜
            movieGradeList = gradeService.sortMovieByMonthPopularity();
        } else {
            // 总榜
            movieGradeList = movieService.showAllMovie();
        }
        redisTemplate.opsForValue().set("movieGrade", movieGradeList);
        return movieGradeList;
    }
}
